<template>
  <div class="search-container">
    <!-- 搜索组件 -->
    <!-- 增加这个form标签，目的是为了让其唤起键盘的时候出现搜索二字 -->
    <form action="/">
      <van-search
        background="#3296fa"
        v-model="searchValue"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="$router.back()"
        @clear="isResultShow=false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result 
      :search-value="searchValue" 
      v-if="isResultShow" 
    />
    <!-- /搜索结果 -->

    <!-- 搜索建议 -->
    <search-suggestion 
      :search-value="searchValue" 
      @search="onSearch"
      v-else-if="searchValue" 
    />
    <!-- /搜索建议 -->

    <!-- 搜索历史 -->
    <search-history 
      :history-list="historyList" 
      @search="onSearch"
      v-else 
    />
    <!-- /搜索历史 -->

  </div>
</template>
<script>
import SearchHistory from './components/search-history'
import SearchResult from './components/search-result'
import searchSuggestion from './components/search-suggestion'
import { getItem,setItem } from '@/utils/storage'
  export default {
    components: { searchSuggestion, SearchHistory, SearchResult },
    name:'Search',
    data() {
      return {
        searchValue: '',  // 输入框绑定数据
        isResultShow:false,  // 搜索结果是否展示
        historyList: getItem('TOUTIAO_SEARCH')  || []   // 历史记录
      }
    },
    created () {
      console.log('搜索被创建了');
    },
    watch:{
      historyList:{
        deep:true,
        handler(){
          setItem('TOUTIAO_SEARCH',this.historyList)
        }
      }
    },
    methods: {
      onSearch(val) {
        // 接收子组件传递出来的数据给搜索变量
        this.searchValue = val
        // 搜索结果打开
        this.isResultShow = true
        // 增加历史记录(去重)
        !this.historyList.includes(val) && this.historyList.unshift(val)
      }
    },
  }
</script>

<style lang="less" scoped>
.van-search__action{
  color: #fff;
}
</style>